﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Data;

using NHibernate;
using NHibernate.Linq;

using Common.Model;
using Common.Error;
using OpenAPI.Model.OAuth;
using OpenAPI.IDAL.OAuth;
using DBUtility;

namespace OpenAPI.NhiDAL.OAuth
{
    public class ConsumerDAL : IConsumer
    {

        #region 消费方管理

        /// <summary>
        /// 注册消费方
        /// </summary>
        /// <param name="info"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool ConsumerRegister(ConsumerInfo info, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerInfo consumer_ex = (from c in session.Query<ConsumerInfo>()
                                        where c.CONSUMER_NAME == info.CONSUMER_NAME
                                        select c).SingleOrDefault();

            if (consumer_ex == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        //insert
                        session.Save(info);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch (HibernateException)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "存在同名消费方");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 获取消费方信息
        /// </summary>
        /// <param name="oauth_consumer_key"></param>
        /// <param name="oauth_consumer_secret"></param>
        /// <returns></returns>
        public ConsumerInfo GetConsumer(string oauth_consumer_key, string oauth_consumer_secret)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            ConsumerInfo consumer = (from c in session.Query<ConsumerInfo>()
                                     where c.OAUTH_CONSUMER_KEY == oauth_consumer_key
                                     && c.OAUTH_CONSUMER_SECRET == oauth_consumer_secret
                                     select c).SingleOrDefault();
            NHibernateHelper.CloseSession();

            return consumer;
        }

        /// <summary>
        /// 消费方清单
        /// </summary>
        /// <returns></returns>
        public IList<ConsumerInfo> GetConsumers()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<ConsumerInfo> consumers = (from c in session.Query<ConsumerInfo>()
                                             select c).ToList();
            NHibernateHelper.CloseSession();

            return consumers;
        }

        /// <summary>
        /// 修改消费方
        /// </summary>
        /// <param name="info"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool ConsumerModify(ConsumerInfo info, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerInfo consumer_ex = (from c in session.Query<ConsumerInfo>()
                                        where c.OAUTH_CONSUMER_KEY == info.OAUTH_CONSUMER_KEY
                                        && c.OAUTH_CONSUMER_SECRET == info.OAUTH_CONSUMER_SECRET
                                        select c).SingleOrDefault();

            if (consumer_ex != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        consumer_ex.CONSUMER_REQUEST_URL = info.CONSUMER_REQUEST_URL;
                        consumer_ex.CONSUMER_CALLBACK_URL = info.CONSUMER_CALLBACK_URL;
                        consumer_ex.CONSUMER_NAME = info.CONSUMER_NAME;
                        consumer_ex.CONSUMER_LEVEL = info.CONSUMER_LEVEL;
                        consumer_ex.CONSUMER_EMAIL = info.CONSUMER_EMAIL;

                        //Update
                        session.Update(consumer_ex);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch (HibernateException)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此消费方");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 删除消费方
        /// </summary>
        /// <param name="oauth_consumer_key"></param>
        /// <param name="oauth_consumer_secret"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool DeleteConsumer(string oauth_consumer_key, string oauth_consumer_secret, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerInfo consumer = (from c in session.Query<ConsumerInfo>()
                                     where c.OAUTH_CONSUMER_KEY == oauth_consumer_key
                                     && c.OAUTH_CONSUMER_SECRET == oauth_consumer_secret
                                     select c).SingleOrDefault();

            if (consumer != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        //删除Token
                        session.Delete(" from AuthorizeTokenInfo t where t.OAUTH_CONSUMER_KEY = ? ", oauth_consumer_key, NHibernateUtil.String);

                        //删除消费方
                        session.Delete(consumer);

                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch (HibernateException)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此消费方");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        #endregion

        #region 令牌、密钥

        /// <summary>
        /// 获取消费方密钥
        /// </summary>
        /// <param name="oauth_consumer_key">消费方键值</param>
        /// <param name="error"></param>
        /// <returns></returns>
        public string GetOAuthConsumerSecret(string oauth_consumer_key, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            error = null;
            string secret = "";

            ConsumerInfo consumer = session.Query<ConsumerInfo>().SingleOrDefault(c => c.OAUTH_CONSUMER_KEY == oauth_consumer_key);

            if (consumer != null)
            {
                secret = consumer.OAUTH_CONSUMER_SECRET;
                error = null;
            }
            else
            {
                error = ErrorHelper.NewError("", "不存在此Key的密钥");
            }
            NHibernateHelper.CloseSession();

            return secret;
        }

        /// <summary>
        /// 获取令牌密钥
        /// </summary>
        /// <param name="oauth_consumer_key">消费方键值</param>
        /// <param name="oauth_token">令牌</param>
        /// <returns></returns>
        public string GetOAuthTokenSecret(string oauth_consumer_key, string oauth_token, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            error = ErrorHelper.INVALID_EXPIRED_TOKEN;
            string secret = "";

            AuthorizeTokenInfo token = session.Query<AuthorizeTokenInfo>().SingleOrDefault(
                t => t.OAUTH_CONSUMER_KEY == oauth_consumer_key
                    && t.OAUTH_TOKEN == oauth_token);

            if (token != null)
            {
                secret = token.OAUTH_TOKEN_SECRET;
                error = null;
            }
            NHibernateHelper.CloseSession();

            return secret;
        }


        /// <summary>
        /// 验证Token是否合法
        /// </summary>
        /// <param name="oauth_consumer_key"></param>
        /// <param name="oauth_token"></param>
        /// <returns></returns>
        public bool ChkOAuthToken(string oauth_consumer_key, string oauth_token)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool _flag = false;

            AuthorizeTokenInfo token = session.Query<AuthorizeTokenInfo>().SingleOrDefault(
                t => t.OAUTH_CONSUMER_KEY == oauth_consumer_key
                && t.OAUTH_TOKEN == oauth_token);

            //不存在
            if (token == null)
            {
                _flag = false;
            }
            else if (token.OAUTH_TOKEN_STATUS == 0)
            {
                //未验证
                _flag = false;
            }
            else
            {
                //判断token是否过期
                long authorize_token_timeout = long.Parse(ConfigurationManager.AppSettings["AUTHORIZE_TOKEN_TIMEOUT"].ToString()) * 60; //秒

                if ((this.GetTimeStemp() - token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP) > authorize_token_timeout)
                {
                    using (ITransaction trans = session.BeginTransaction())
                    {
                        try
                        {
                            _flag = false;

                            //更新Token状态
                            token.OAUTH_TOKEN_STATUS = 0;
                            token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = 0;

                            session.Update(token);
                            session.Flush();
                            trans.Commit();
                        }
                        catch (HibernateException)
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
                else
                {
                    _flag = true;
                }
            }
            NHibernateHelper.CloseSession();

            return _flag;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private long GetTimeStemp()
        {
            TimeSpan ts = DateTime.Now - Convert.ToDateTime("1970-01-01");
            return (long)ts.TotalSeconds;
        }

        /// <summary>
        /// 获取请求令牌
        /// </summary>
        /// <param name="oauth_consumer_key">消费方键值</param>
        /// <param name="newToken">新生成的Token</param>
        /// <param name="error"></param>
        /// <returns></returns>
        public AuthorizeTokenInfo RequestToken(string oauth_consumer_key, AuthorizeTokenInfo newToken, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            error = ErrorHelper.INVALID_CONSUMER_KEY_SECRET;

            AuthorizeTokenInfo exists_token = null;

            //判断消费方是否合法
            ConsumerInfo consumer = session.Query<ConsumerInfo>().SingleOrDefault(
                c => c.OAUTH_CONSUMER_KEY == oauth_consumer_key);
            if (consumer != null)
            {
                //判断Token是否产生过
                exists_token = session.Query<AuthorizeTokenInfo>().SingleOrDefault(
                    t => t.OAUTH_CONSUMER_KEY == oauth_consumer_key);
                try
                {
                    //是否产生过Token
                    if (exists_token != null)
                    {
                        #region 产生过

                        //获取Token有效期
                        long request_token_timeout = long.Parse(ConfigurationManager.AppSettings["REQUEST_TOKEN_TIMEOUT"].ToString()) * 60; //秒
                        long authorize_token_timeout = long.Parse(ConfigurationManager.AppSettings["AUTHORIZE_TOKEN_TIMEOUT"].ToString()) * 60; //秒

                        //判断是否验证过
                        if (exists_token.OAUTH_TOKEN_STATUS == 1)
                        {
                            #region 已验证
                            //判断Token是否过期（即：此次请求时间戳 与 上次验证通过的时间戳 是否超过 Token有效期）
                            if ((newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP - exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP) > authorize_token_timeout)
                            {
                                using (ITransaction trans = session.BeginTransaction())
                                {
                                    try
                                    {
                                        //Token已过期，则产生新的Token
                                        exists_token.OAUTH_TOKEN = newToken.OAUTH_TOKEN;
                                        exists_token.OAUTH_TOKEN_SECRET = newToken.OAUTH_TOKEN_SECRET;
                                        exists_token.OAUTH_TOKEN_STATUS = newToken.OAUTH_TOKEN_STATUS;
                                        exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP = newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP;
                                        exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = newToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                        exists_token.OAUTH_NONCE = newToken.OAUTH_NONCE;

                                        session.Update(exists_token);
                                        session.Flush();
                                        trans.Commit();

                                        error = null;
                                    }
                                    catch (HibernateException)
                                    {
                                        trans.Rollback();
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                //Token未过期，可以继续使用
                                error = null;
                            }
                            #endregion
                        }
                        else
                        {
                            #region 未验证

                            //判断Token是否在请求期内：此次请求的时间戳是否 大于 已存在Token上一次请求的时间戳
                            if (newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP < exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP)
                            {
                                using (ITransaction trans = session.BeginTransaction())
                                {
                                    try
                                    {
                                        //时间戳非法，则产生新的Token
                                        exists_token.OAUTH_CONSUMER_KEY = newToken.OAUTH_CONSUMER_KEY;
                                        exists_token.OAUTH_TOKEN = newToken.OAUTH_TOKEN;
                                        exists_token.OAUTH_TOKEN_SECRET = newToken.OAUTH_TOKEN_SECRET;
                                        exists_token.OAUTH_TOKEN_STATUS = newToken.OAUTH_TOKEN_STATUS;
                                        exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP = newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP;
                                        exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = newToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                        exists_token.OAUTH_NONCE = newToken.OAUTH_NONCE;

                                        session.Update(exists_token);
                                        session.Flush();
                                        trans.Commit();

                                        error = null;
                                    }
                                    catch (HibernateException)
                                    {
                                        trans.Rollback();
                                        throw;
                                    }
                                }
                            }
                            else if ((newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP - exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP) > request_token_timeout)
                            {
                                using (ITransaction trans = session.BeginTransaction())
                                {
                                    try
                                    {
                                        //Token过期，产生新的Token
                                        exists_token.OAUTH_CONSUMER_KEY = newToken.OAUTH_CONSUMER_KEY;
                                        exists_token.OAUTH_TOKEN = newToken.OAUTH_TOKEN;
                                        exists_token.OAUTH_TOKEN_SECRET = newToken.OAUTH_TOKEN_SECRET;
                                        exists_token.OAUTH_TOKEN_STATUS = newToken.OAUTH_TOKEN_STATUS;
                                        exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP = newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP;
                                        exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = newToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                        exists_token.OAUTH_NONCE = newToken.OAUTH_NONCE;

                                        session.Update(exists_token);
                                        session.Flush();
                                        trans.Commit();

                                        error = null;
                                    }
                                    catch (HibernateException)
                                    {
                                        trans.Rollback();
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                using (ITransaction trans = session.BeginTransaction())
                                {
                                    try
                                    {
                                        exists_token.OAUTH_TOKEN_STATUS = newToken.OAUTH_TOKEN_STATUS;
                                        exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = newToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                        exists_token.OAUTH_NONCE = newToken.OAUTH_NONCE;

                                        session.Update(exists_token);
                                        session.Flush();
                                        trans.Commit();

                                        error = null;
                                    }
                                    catch (HibernateException)
                                    {
                                        trans.Rollback();
                                        throw;
                                    }
                                }
                            }

                            #endregion
                        }

                        #endregion
                    }
                    else
                    {
                        #region 未产生过

                        using (ITransaction trans = session.BeginTransaction())
                        {
                            try
                            {
                                //insert
                                exists_token = new AuthorizeTokenInfo();
                                exists_token.OAUTH_CONSUMER_KEY = newToken.OAUTH_CONSUMER_KEY;
                                exists_token.OAUTH_TOKEN = newToken.OAUTH_TOKEN;
                                exists_token.OAUTH_TOKEN_SECRET = newToken.OAUTH_TOKEN_SECRET;
                                exists_token.OAUTH_TOKEN_STATUS = newToken.OAUTH_TOKEN_STATUS;
                                exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP = newToken.OAUTH_TOKEN_REQUEST_TIMESTAMP;
                                exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = newToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                exists_token.OAUTH_NONCE = newToken.OAUTH_NONCE;

                                session.Save(exists_token);
                                session.Flush();
                                trans.Commit();

                                error = null;
                            }
                            catch (HibernateException)
                            {
                                trans.Rollback();
                                throw;
                            }
                        }

                        #endregion
                    }
                }
                catch
                {
                    exists_token = null;
                    error = ErrorHelper.NewError("", "生成令牌及密钥失败");
                }
            }
            else
            {
                exists_token = null;
                error = ErrorHelper.INVALID_CONSUMER_KEY_SECRET;
            }
            NHibernateHelper.CloseSession();

            //返回令牌
            return exists_token;
        }

        /// <summary>
        /// 验证请求令牌
        /// </summary>
        /// <param name="authToken">欲验证的Token</param>
        /// <param name="error"></param>
        /// <returns></returns>
        public AuthorizeTokenInfo AuthorizeToken(AuthorizeTokenInfo authToken, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            error = ErrorHelper.INVALID_EXPIRED_TOKEN;

            AuthorizeTokenInfo exists_token = null;

            //判断Token是否产生过
            exists_token = session.Query<AuthorizeTokenInfo>().SingleOrDefault(
                t => t.OAUTH_CONSUMER_KEY == authToken.OAUTH_CONSUMER_KEY
                    && t.OAUTH_TOKEN == authToken.OAUTH_TOKEN
                    && t.OAUTH_TOKEN_SECRET == authToken.OAUTH_TOKEN_SECRET);
            try
            {
                if (exists_token != null)
                {
                    //判断request token是否过期
                    long request_token_timeout = long.Parse(ConfigurationManager.AppSettings["REQUEST_TOKEN_TIMEOUT"].ToString()) * 60; //秒
                    long authorize_token_timeout = long.Parse(ConfigurationManager.AppSettings["AUTHORIZE_TOKEN_TIMEOUT"].ToString()) * 60; //秒


                    //判断是否验证过
                    if (exists_token.OAUTH_TOKEN_STATUS == 1)
                    {
                        #region 已验证

                        //判断是否过期
                        if ((authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP - exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP) > authorize_token_timeout)
                        {
                            using (ITransaction trans = session.BeginTransaction())
                            {
                                try
                                {
                                    //过期
                                    exists_token.OAUTH_TOKEN_STATUS = 0;
                                    exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                    exists_token.OAUTH_NONCE = authToken.OAUTH_NONCE;

                                    session.Update(exists_token);
                                    session.Flush();
                                    trans.Commit();

                                    exists_token = null;
                                    error = ErrorHelper.INVALID_EXPIRED_TOKEN;
                                }
                                catch (HibernateException)
                                {
                                    trans.Rollback();
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            using (ITransaction trans = session.BeginTransaction())
                            {
                                try
                                {
                                    //未过期
                                    exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                    exists_token.OAUTH_NONCE = authToken.OAUTH_NONCE;

                                    session.Update(exists_token);
                                    session.Flush();
                                    trans.Commit();
                                }
                                catch (HibernateException)
                                {
                                    trans.Rollback();
                                    throw;
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region 未验证

                        //判断时间戳是否合法
                        if (exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP >= authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP)
                        {
                            exists_token = null;
                            error = ErrorHelper.INVALID_EXPIRED_TOKEN;
                        }
                        else if ((authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP - exists_token.OAUTH_TOKEN_REQUEST_TIMESTAMP) > request_token_timeout)
                        {
                            exists_token = null;
                            error = ErrorHelper.INVALID_EXPIRED_TOKEN;
                        }
                        else
                        {
                            using (ITransaction trans = session.BeginTransaction())
                            {
                                try
                                {
                                    //update
                                    exists_token.OAUTH_TOKEN_STATUS = 1;
                                    exists_token.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP = authToken.OAUTH_TOKEN_AUTHORIZE_TIMESTAMP;
                                    exists_token.OAUTH_NONCE = authToken.OAUTH_NONCE;

                                    session.Update(exists_token);
                                    session.Flush();
                                    trans.Commit();

                                    error = null;
                                }
                                catch (HibernateException)
                                {
                                    trans.Rollback();
                                    throw;
                                }
                            }
                        }
                        #endregion
                    }
                }
            }
            catch
            {
                exists_token = null;
                error = ErrorHelper.NewError("", "验证令牌及密钥失败");
            }
            //close session
            NHibernateHelper.CloseSession();

            //返回令牌
            return exists_token;
        }

        /// <summary>
        /// 换取访问令牌
        /// </summary>
        /// <param name="oauth_token">令牌</param>
        /// <param name="oauth_token_secret">令牌密钥</param>
        /// <returns></returns>
        public AuthorizeTokenInfo ExchangeAccessToken(string oauth_token, string oauth_token_secret)
        {
            AuthorizeTokenInfo token = null;

            return token;
        }

        #endregion

        #region 消费方等级方法

        /// <summary>
        /// 新增消费方等级
        /// </summary>
        /// <param name="level"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool InsertConsumerLevel(ConsumerLevelInfo level, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerLevelInfo exists_lvl = session.Query<ConsumerLevelInfo>().SingleOrDefault(l => l.CONSUMER_LEVEL == level.CONSUMER_LEVEL);
            if (exists_lvl == null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(level);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch (HibernateException)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "已存在此编号的级别");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 更新消费方等级
        /// </summary>
        /// <param name="level"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool UpdateConsumerLevel(ConsumerLevelInfo level, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerLevelInfo exists_lvl = session.Query<ConsumerLevelInfo>().SingleOrDefault(l => l.CONSUMER_LEVEL == level.CONSUMER_LEVEL);
            if (exists_lvl != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        exists_lvl.CONSUMER_LEVEL_NAME = level.CONSUMER_LEVEL_NAME;
                        exists_lvl.CONSUMER_LEVEL_DESC = level.CONSUMER_LEVEL_DESC;

                        session.Update(exists_lvl);
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch (HibernateException)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此编号的级别");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 删除消费方等级，同时删除所属方法
        /// </summary>
        /// <param name="consumer_level"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool DeleteConsumerLevel(string consumer_level, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            ConsumerLevelInfo exists_lvl = session.Query<ConsumerLevelInfo>().SingleOrDefault(l => l.CONSUMER_LEVEL == consumer_level);
            if (exists_lvl != null)
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    try
                    {
                        //delete consumer level
                        session.Delete(exists_lvl);

                        //delete methods in level
                        session.Delete(" from MethodInConsumerLevelInfo m where m.MethodInConsumerLevelPK.CONSUMER_LEVEL = ? ", consumer_level, NHibernateUtil.String);
                        
                        session.Flush();
                        trans.Commit();

                        result_stat = true;
                        error = null;
                    }
                    catch
                    {
                        trans.Rollback();

                        result_stat = false;
                        error = ErrorHelper.NewError("", "数据库操作时报错");
                    }
                }
            }
            else
            {
                result_stat = false;
                error = ErrorHelper.NewError("", "不存在此编号的级别");
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        /// <summary>
        /// 获取消费方等级列表
        /// </summary>
        /// <returns></returns>
        public IList<ConsumerLevelInfo> GetConsumerLevels()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<ConsumerLevelInfo> lvls = (from l in session.Query<ConsumerLevelInfo>()
                                             select l).ToList();
            NHibernateHelper.CloseSession();

            return lvls;
        }

        /// <summary>
        /// 获取消费方等级
        /// </summary>
        /// <param name="consumer_level"></param>
        /// <returns></returns>
        public ConsumerLevelInfo GetConsumerLevel(string consumer_level)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            ConsumerLevelInfo lvl = session.Query<ConsumerLevelInfo>().SingleOrDefault(
                l => l.CONSUMER_LEVEL == consumer_level);
            NHibernateHelper.CloseSession();

            return lvl;
        }

        /// <summary>
        /// 方法包含在消费方Level中
        /// </summary>
        /// <param name="oauth_consumer_key"></param>
        /// <param name="method_name"></param>
        /// <returns></returns>
        public bool ContainsMethodInConsumerLevel(string oauth_consumer_key, string method_name)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;

            ConsumerInfo consumer = session.Query<ConsumerInfo>().SingleOrDefault(c => c.OAUTH_CONSUMER_KEY == oauth_consumer_key);
            if (consumer != null)
            {
                MethodInConsumerLevelInfo exists_m = session.Query<MethodInConsumerLevelInfo>().SingleOrDefault(
                    m => m.MethodInConsumerLevelPK.METHOD_NAME.ToLower() == method_name
                        && m.MethodInConsumerLevelPK.CONSUMER_LEVEL == consumer.CONSUMER_LEVEL);
                if (exists_m != null)
                {
                    result_stat = true;
                }
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }



        /// <summary>
        /// 获取消费方Level中的方法
        /// </summary>
        /// <param name="consumer_level"></param>
        /// <returns></returns>
        public IList<MethodInConsumerLevelInfo> GetMethodsInConsumerLevel(string consumer_level)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            IList<MethodInConsumerLevelInfo> methods = (from m in session.Query<MethodInConsumerLevelInfo>()
                                                        where m.MethodInConsumerLevelPK.CONSUMER_LEVEL == consumer_level
                                                        select m).ToList();
            NHibernateHelper.CloseSession();

            return methods;
        }

        /// <summary>
        /// 设置消费方Level的方法-保存
        /// </summary>
        /// <param name="consumer_level"></param>
        /// <param name="arr_method"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool SaveMethodsToConsumerLevel(string consumer_level, string[] arr_method, out ErrorType error)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            bool result_stat = false;
            error = null;

            using (ITransaction trans = session.BeginTransaction())
            {
                try
                {
                    //清空原来设置，采用批量删除
                    session.Delete(" from MethodInConsumerLevelInfo m where m.MethodInConsumerLevelPK.CONSUMER_LEVEL = ? ", consumer_level, NHibernateUtil.String);
                    session.Flush();    //因为后面要进行插入，所以必须提交语句执行

                    //插入新设置
                    foreach (string method_name in arr_method)
                    {
                        MethodInConsumerLevelInfo m = new MethodInConsumerLevelInfo();
                        MethodInConsumerLevelInfoPK pk = new MethodInConsumerLevelInfoPK();
                        pk.CONSUMER_LEVEL = consumer_level;
                        pk.METHOD_NAME = method_name;
                        m.MethodInConsumerLevelPK = pk;

                        session.Save(m);
                        session.Flush();
                    }

                    trans.Commit();

                    result_stat = true;
                    error = null;
                }
                catch
                {
                    result_stat = false;
                    error = ErrorHelper.NewError("", "Database Error");
                }
            }
            NHibernateHelper.CloseSession();

            return result_stat;
        }

        #endregion

    }//
}//
